<template>
  <div>
    <div class="form-item">
      <div class="title">ntp服务配置</div>
      <d-form :options="options" class="edit-form"/>
    </div>
    <el-button type="primary" class="submit-button" :color="formOptions.buttonColor" @click="submitForm">提交</el-button>
  </div>
</template>

<script setup lang="ts">
  import {reactive, ref, watchEffect,watch} from 'vue'
  import {updateConfig} from '@/api/site'
  import {ElMessage, FormInstance} from "element-plus";
  import {communicationType,configType,targetType} from '@/utils/deviceConfig'

  let props = defineProps({
    options:{
      type:Object
    },
    params:{
      type:Object,
      default:{
        id:'',            // 站点的id/省份的code
        targetType:'',    // province 省份，device设备
      }         
    },
    config:{
      type:Object
    }
  });

  let formOptions = props.options;
  let form = reactive({})

  watch(
    ()=>props.config,
    (val)=>{
      if(val.ntp){
        form = Object.assign(form,val.ntp)
      }
    },
    {
      deep:true
    }
  )

  const options = {
    labelWidth: '120px',
    inline: formOptions.inline,
    labelPosition: formOptions.labelPosition,
    formRef: ref<FormInstance>(),
    formClass: formOptions.formClass,
    size: formOptions.size,
    formItems: [
      {
        label: 'NTP主服务',
        prop: 'master',
        component: 'd-input',
        options: {
          placeholder: '请输入NTP主服务地址',
        },
        rules: {
          required: true,
          message: '请输入NTP主服务地址',
          trigger: 'change',
        },
        disabled: false
      }, {
        label: 'NTP备用服务',
        prop: 'slave',
        component: 'd-input',
        options: {
          placeholder: '请输入NTP备用服务地址',
        },
        rules: {
          required: true,
          message: '请输入NTP备用服务地址',
          trigger: 'change',
        },
        disabled: false
      }
    ],
    form: form
  }

  const submitForm = async () => {
    let formEl = options.formRef?.value;
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        updateData(options.form)
      }
    })
  }

  type paramsType = {
    configType:number,
    id:string,
    targetType:string,
    [propName:string]:any,
  }
  const updateData = (data)=>{
    let params:paramsType = {
      configType:configType['ntp'],
      id:props.params.id,
      targetType:targetType[props.params.targetType],
      ntp: data
    }
    updateConfig(params).then(res=>{
      ElMessage.success('更新成功！')
    })
  }

  const resetForm = () => {
    let formEl = options.formRef?.value;
    if (!formEl) return
    formEl.resetFields()
  }

 
</script>
